import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vape_xe/routes/app_pages.dart';
import 'package:vape_xe/values/values.dart';

import 'logic.dart';

class HomeView extends GetView<HomeController> {
  const HomeView({super.key});

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (_, __) => controller.onPopInvoked(),
      child: GetRouterOutlet.builder(
        route: Routes.HOME,
        builder: (context) {
          return Scaffold(
            body: GetRouterOutlet(
              initialRoute: Routes.EARN,
              anchorRoute: Routes.HOME,
              filterPages: (pages) {
                //保存页面状态的关键
                var ret = pages.toList();
                final nav = Get.nestedKey(Routes.HOME)?.navigatorKey.currentState?.widget;
                Get.log('Home filter pages: ${pages.map((e) => e.name)}');

                if (nav != null) {
                  if (ret.isEmpty) {
                    Get.log("Home use olds: ${nav.pages.map((e) => e.name)}");
                    return nav.pages as List<GetPage>;
                  }
                  final sn = ret[0].name.split('/').length;
                  for (var p in nav.pages as List<GetPage>) {
                    if (p.maintainState && p.name.split('/').length == sn && !ret.contains(p)) {
                      ret.insert(0, p);
                    }
                  }
                }
                ret = ret.where((e) => e.participatesInRootNavigator != true).toList();
                Get.log('Home real pages: ${ret.map((e) => e.name)}');
                return ret;
              },
            ),
            bottomNavigationBar: IndexedRouteBuilder(
              routes: const [Routes.EARN, Routes.SCAN, Routes.PLAYGROUND],
              builder: (context, routes, index) {
                return BottomNavigationBar(
                  items: controller.bottomTabs,
                  currentIndex: index,
                  backgroundColor: AppColors.scaffoldBackground,
                  fixedColor: AppColors.primaryText,
                  type: BottomNavigationBarType.fixed,
                  onTap: (position) {
                    if (position == 1) {
                      controller.toName(routes[position]);
                    } else {
                      Get.offAllNamed(routes[position]);
                    }
                  },
                  showSelectedLabels: false,
                  showUnselectedLabels: false,
                );
              },
            ),
          );
        },
      ),
    );
  }
}
